$(function(){
	
	var listArr = [{
        "sClass": "text-left",
        "data": "id",
        "render": function (data, type, full, meta) {
            return '<input type="checkbox"  class="checkchild"  value="' + data + '" id="check' + data + '"/>';
        },
        "bSortable": false
    },{
    	"sClass": "text-left",
        "data": "loginName"
    },{
    	"sClass": "text-left",
        "data": "empNo"
    },{
    	"sClass": "text-left",
        "data": "empName"
    },{
    	"sClass": "text-left",
        "data": "state",
        "render":function(data, type, full, meta){
        	if(data == 0){
        		return '<button type="button" onclick="userOn(\'' + full.id + '\',event)">启用</button>'
        	}else{
        		return '<button type="button" onclick="userOn(\'' + full.id + '\',event)">禁用</button>'
        	}
        }
    }];
	
	var userTable = function(){
		return matchTable('#datatables','/user/listData.do',listArr, function(obj){}, false);
	}
	
	userTable();
	
	ajaxSer.userRoleInit(function(data){
		var liList = "";
		var userData = data.data;
		for(var i=0; i<userData.length; i++){
			liList += '<li><label><input type="checkbox" id="'+ userData[i].id +'">  '+ userData[i].sysRoleName  +'</label></li>';
		}
		$(".roletouser ul").append(liList);
	});
	//新增
	$(".useradd").on('click',function(){
		layer.open({
	    	  title: '新增', 
			  skin: 'demo-class',
			  area: ['400px', '400px'],
			  btn: ['确认', '取消'],
			  content: $(".userform").html(),
			  success: function(layero, index){
				  $(layero).find("#empNo").select2({			  
			            ajax: {
			                url: webroot+ "/select/getEmployeeByName.ajax",
			                type:'POST',
			                data: function (params) {		                	
			                    params.rows=10;
			                    return {
			                    	searchName:params.term || '', // search term
			                    	currentPage:(params.page||1)-1,
			                    	pageSize:params.rows
			                    };
			                },
			                processResults: function (data, params) {
			                	
			                	var processData = JSON.parse(data);
			                	params.page = params.page || 1;
			                	var selectArr = [];
		                    	var newData=processData.data;
					    		for(var i=0; i<newData.length; i++){
					    			selectArr.push({'id':newData[i].employeeSn,'text':newData[i].employeeName,'deptPah':newData[i].deptPah})
					    		}
			                    return {
			                        results: selectArr,
			                        pagination: {	
			                            more: (params.page * params.rows) < processData.count
			                        }
			                    };
			                }
			            },		            
			            escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
			            templateResult: function (state){
			                if (!state.id) { return state.text; }
			                var $state = $(
			                    '<p>' + state.text + '</p><p style="word-break:break-all;color:#999;">'+state.deptPah+'</p>'
			                );
			                return $state;
			            }
			        });
				    $(layero).find('#adduserdio').validate({
				    	rules: {
					    	confirm_password:{
						        equalTo: $(layero).find('#adduserdio').find("#password")
						    }
				    	}
				    });
			  },
			  yes:function(index, layero){
				  //这里是回调，点击确认的时候执行的方法，最后一个关闭需要手动调用
				  if($(layero).find('#adduserdio').valid()){
					  var checkedAll = $(".roletouser input");
					  var roleList = [];
					  for(var i=0; i<checkedAll.length; i++){
						  if($(checkedAll[i]).prop('checked')){
							  roleList.push($(checkedAll[i]).attr('id'));
						  }
					  }
					  roleList = roleList.join();
					  
					  var userListTree = $.extend({},{'roleIds':roleList},$(layero).find('form').serializeObject());
					  
					  ajaxSer.userAdd(userListTree, function(data){
						  if(data.type == "2"){
							 userTable().draw();
						  }
						  layer.msg(data.msg);
					  })
					  layer.close(index);
				  }
			  },
			  cancel:function(index){
				  layer.close(index);
			  }
			});
	});
	
	//修改
	$(".useredit").on('click',function(){
		var choose_a = $('#datatables tbody :checkbox:checked');
        var c_tIds;
        c_tIds = choose_a.eq(0).val();
        if (c_tIds == undefined || $.trim(c_tIds) == "") {
        	layer.msg("请选择一条记录！");
            return false;
        }
        if(choose_a.length != 1){
        	layer.msg("只能选择一条记录！");
            return false;
        }
    	layer.open({
    	  title: '修改', 
  		  skin: 'demo-class',
  		  btn: ['确认', '取消'],
  		  content: $(".userform").html(),
  		  success: function(layero, index){
  			//修改之前执行填充操作
  			$(layero).find('#adduserdio').validate({
		    	rules: {
			    	confirm_password:{
				        equalTo: $(layero).find('#adduserdio').find("#password")
				    }
		    	}
		    });
  			$(layero).find("#empNo").select2({			  
	            ajax: {
	                url: webroot+ "/select/getEmployeeByName.ajax",
	                type:'POST',
	                data: function (params) {		                	
	                    params.rows=10;
	                    return {
	                    	searchName:params.term || '',
	                    	currentPage:(params.page||1)-1,
	                    	pageSize:params.rows
	                    };
	                },
	                processResults: function (data, params) {	                	
	                	var processData = JSON.parse(data);
	                	params.page = params.page || 1;
	                	var selectArr = [];
                    	var newData=processData.data;
			    		for(var i=0; i<newData.length; i++){
			    			selectArr.push({'id':newData[i].employeeSn,'text':newData[i].employeeName,'deptPah':newData[i].deptPah})
			    		}
	                    return {
	                        results: selectArr,
	                        pagination: {	
	                            more: (params.page * params.rows) < processData.count
	                        }
	                    };
	                }
	            },		            
	            templateResult: function (state){
	                if (!state.id) { return state.text; }
	                var $state = $(
	                    '<p>' + state.text + '</p><p style="word-break:break-all;color:#999;">'+state.deptPah+'</p>'
	                );
	                return $state;
	            }
	        });
//  			if(obj.empName!=null){
//				$(layero).find("#empId").html('<option value="' + obj.empId + '">' + obj.empName + '</option>').trigger("change");
//			}
  			ajaxSer.userEditBefore(c_tIds,function(data){
//  				console.log(JSON.stringify(data));
  				var nameVal = $(layero).find('form input');
				for(var i=0; i<nameVal.length;i++){
					if(data[$(nameVal[i]).attr('name')]){
						$(nameVal[i]).val(data[$(nameVal[i]).attr('name')])
					}
				}
				$(layero).find("#confirm_password").val(data.password);
				var rolechecked = $(".roletouser input");
				if(data.roleIds){
					var roleArr = data.roleIds.split(",");
					for(var j=0; j<rolechecked.length; j++){
						if(roleArr.indexOf($(rolechecked[j]).attr("id")) != -1){
							$(rolechecked[j]).prop('checked',true);
						}
					}
				}
  			})
  		  },
  		  yes:function(index, layero){
  			if($(layero).find('#adduserdio').valid()){
	  			var checkedAll = $(layero).find('input');
			    var roleList = [];
			    for(var i=0; i<checkedAll.length; i++){
				    if($(checkedAll[i]).prop('checked')){
					    roleList.push($(checkedAll[i]).attr('id'));
				    }
			    }
			    roleList = roleList.join();
	  			var treeJson = $.extend({},{'id':c_tIds,'roleIds':roleList},$(layero).find('form').serializeObject());
	  			
	  			ajaxSer.userEdit(treeJson, function(data){
	  				if(data.type == "2"){
	  					userTable().draw();
					}
					layer.msg(data.msg);
	  			})
	  			layer.close(index);
  			}
  		  },
  		  cancel:function(index){
  			  layer.close(index);
  		  }
  		});
	});
	
	//删除
	$(".userdel").on('click',function(){
		
		var del_tIds = "";
        var data_a = $("#datatables tbody :checkbox:checked");
        $.each(data_a, function (n) {
            if (n == 0) {
                del_tIds = data_a.eq(n).val();
            } else {
                del_tIds = del_tIds + "," + data_a.eq(n).val();
            }
        })
        if (del_tIds == undefined || $.trim(del_tIds) == "") {
        	layer.msg("请选择一条记录！");
            return false;
        }
    	layer.confirm('确认删除?', {icon: 3, title:'删除'}, function(index){
    		var delTree = {
    				'uIds':del_tIds,
    				'method':'delete'
    		}
    		ajaxSer.userDel(delTree, function(data){
    			if(data.type == "2"){
					userTable().draw();
				}
				layer.msg(data.msg);
    		})
		    layer.close(index);
		});
		
	});
	
	
	//单击行选中事件
    $('#datatables tbody').on('click', 'tr', function () {
        var table = $('#datatables').DataTable();
        var data = table.row(this).data();
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
            $('#check' + data.id).prop("checked", false);
        } else {
            $(this).addClass('selected');
            $('#check' + data.id).prop("checked", true);
        }
    });
    //全选
    $(".checkall").click(function () {
        var check = $(this).prop("checked");
        $(".checkchild").prop("checked", check);
        var cells = new Array();
        $('#datatables tbody tr').each(function () {
            if (check) {
                $(this).addClass('selected');
            } else {
                $(this).removeClass('selected');
            }
        });
    });
});

function userOn(str,e){
	e.stopPropagation();
	var states = "";
	if(e.srcElement.innerHTML == "启用"){
		states = "disable";
		e.srcElement.innerHTML = "禁用";
	}else{
		states = "enable";
		e.srcElement.innerHTML = "启用";
	}
	var params = {"uIds":str,"method":states};
	
	ajaxSer.userOnOff(params, function(data){
		console.log(data);
	});
}